package com.ow.module.event.sysmgr;

import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;

import com.ow.framework.common.Constant;
import com.ow.framework.data.po.ResultData;
import com.ow.framework.exception.DetailException;
import com.ow.framework.listener.event.EventExecutor;
import com.ow.framework.listener.event.EventListener;
import com.ow.framework.util.KeyHelper;




public class RolePermissionMapEvent implements EventListener{

	static Logger log = Logger.getLogger(Constant.FRAMEWORK);
	private ResultData resultData;
	public RolePermissionMapEvent()
	{
		resultData = new ResultData();
	}	
	
	public ResultData event(EventExecutor eventExecutor) throws Exception {
		try
		{
			String autoPrimaryKey = KeyHelper.getKey();
			eventExecutor.getBaseAction().getParamMap().put("autoPrimaryKey", autoPrimaryKey);
			String deletesid = eventExecutor.getSqlidByIndex(0);
			String insertsid = eventExecutor.getSqlidByIndex(1);
			String selectsid = eventExecutor.getSqlidByIndex(2);
			int rvalue = 0;
			if (deletesid != null && !deletesid.equals(""))
			{
				eventExecutor.getSqlSession().insert(deletesid, eventExecutor.getBaseAction().getParamMap());
			}		
			if (selectsid != null && !selectsid.equals(""))
			{
				List resultList = eventExecutor.getSqlSession().selectList(selectsid, eventExecutor.getBaseAction().getParamMap());
				for(int i = 0 ;i<resultList.size(); i++){
					if(resultList.get(i) !=null && !resultList.get(i).equals("")){
						eventExecutor.getBaseAction().getParamMap().put("rpmPmsCode", ((HashMap)resultList.get(i)).get("rpmPmsCode").toString());
						rvalue += eventExecutor.getSqlSession().insert(insertsid, eventExecutor.getBaseAction().getParamMap());
					}
				}
			}
			if (insertsid != null && !insertsid.equals(""))
			{
				String pmsArr [] = eventExecutor.getBaseAction().getParamMap().get("treeCheckboxVal") == null ?new String[1]:eventExecutor.getBaseAction().getParamMap().get("treeCheckboxVal").split(",");
				for (int i=0; i<pmsArr.length; i++)
				{
					if (pmsArr[i] != null && !pmsArr[i].equals("")){
						pmsArr[i] = pmsArr[i].trim();
						eventExecutor.getBaseAction().getParamMap().put("rpmPmsCode", pmsArr[i]);
						rvalue += eventExecutor.getSqlSession().insert(insertsid, eventExecutor.getBaseAction().getParamMap());
					}
				}
				
			}	
			resultData.setIntResult(rvalue);
			return resultData;
		}
		catch (Exception e)
		{
			String error = DetailException.expDetail(e, RolePermissionMapEvent.class);
			log.error(error);
		}
		return resultData;
	}

}
